import { useCallback } from 'react';
import { Alert } from 'react-native';
import { useAppContext } from '../context/AppContext';
import { Task, News } from '../types';
import { delay } from '../utils/helpers';

export const useRefresh = () => {
  const {
    state: { refreshing },
    addTask,
    addNews,
    setRefreshing,
  } = useAppContext();

  // 刷新待办事项
  const refreshTasks = useCallback(async () => {
    setRefreshing(true);
    
    try {
      // 模拟网络请求延迟
      await delay(2000);
      
      // 添加新的示例任务
      const newTask: Task = {
        id: Date.now().toString(),
        title: `刷新任务 ${new Date().toLocaleTimeString()}`,
        completed: false,
        createdAt: new Date().toLocaleString(),
      };
      
      addTask(newTask.title);
      Alert.alert('刷新成功', '已添加新的待办事项');
    } catch (error) {
      Alert.alert('刷新失败', '请检查网络连接');
    } finally {
      setRefreshing(false);
    }
  }, [addTask, setRefreshing]);

  // 刷新新闻
  const refreshNews = useCallback(async () => {
    setRefreshing(true);
    
    try {
      // 模拟网络请求延迟
      await delay(2000);
      
      // 添加新的示例新闻
      const newNews: News = {
        id: Date.now().toString(),
        title: `最新资讯 ${new Date().toLocaleTimeString()}`,
        content: '这是通过下拉刷新获取的最新资讯内容，包含了最新的技术动态和行业资讯...',
        publishTime: new Date().toLocaleString(),
      };
      
      addNews(newNews);
      Alert.alert('刷新成功', '已获取最新资讯');
    } catch (error) {
      Alert.alert('刷新失败', '请检查网络连接');
    } finally {
      setRefreshing(false);
    }
  }, [addNews, setRefreshing]);

  // 通用刷新方法
  const refreshData = useCallback(async () => {
    setRefreshing(true);
    
    try {
      await delay(1500);
      Alert.alert('刷新成功', '数据已更新');
    } catch (error) {
      Alert.alert('刷新失败', '请检查网络连接');
    } finally {
      setRefreshing(false);
    }
  }, [setRefreshing]);

  return {
    refreshing,
    refreshTasks,
    refreshNews,
    refreshData,
  };
};